package com.evil.common.application.enums.form.control;

import com.evil.common.core.enums.BaseEnum;
import com.evil.common.family.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Optional;

/**
 * 表单控件类型分类
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@AllArgsConstructor
public enum ControlTypeEnum {

    /**
     * 表单控件类型分类
     */
    INPUT("INPUT", "输入控件"),
    SELECT("SELECT", "选择控件"),
    SWITCH("SWITCH", "开关控件"),
    SLIDER("SLIDER", "滑块控件"),
    DATE("DATE", "日期控件"),
    RATE("RATE", "评分控件"),
    UPLOAD("UPLOAD", "上传控件"),
    SPECIAL("SPECIAL", "特殊控件"),

    ;
    @Getter
    private final String type;
    @Getter
    private final String name;

    /**
     * 检查当前类型控件 是否兼容转换 指定类型
     *
     * @param type type
     * @return boolean
     */
    public boolean isCompatible(String type) {
        if (StringUtils.isBlank(type)) {
            return true;
        }
        switch (this) {
            case INPUT:
                // 文本类控件 全兼容
                return true;
            case SELECT:
                // 选择类控件 兼容 文本类、选择类、日期类
                return Arrays.asList(INPUT.type, SELECT.type, DATE.type).contains(type);
            case SWITCH:
            case SLIDER:
            case DATE:
            case RATE:
            case UPLOAD:
            case SPECIAL:
                // 其他所有类 只兼容 本类
                return this.type.equals(type);
            default:
                return false;
        }
    }

    public static Optional<ControlTypeEnum> findByCode(String type) {
        if (StringUtils.isBlank(type)) {
            return Optional.empty();
        }
        return Arrays.stream(values()).filter(e -> e.type.equals(type)).findFirst();
    }

    public static ControlTypeEnum isExistByCode(String code) {
        return ControlTypeEnum.findByCode(code).orElseThrow(()
                -> new BusinessException(BaseEnum.ERROR_PARAMETER, "表单控件类型分类参数错误"));
    }
}
